"""
左侧控制面板模块
包含颜色、尺寸、格式和保存设置的所有控件
"""

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, 
                              QLabel, QLineEdit, QPushButton, QComboBox, QSpinBox,
                              QFileDialog)
from PySide6.QtCore import Signal

from ...config.settings import AppConfig
from ...utils.file_utils import FileUtils


class ControlPanel(QWidget):
    """左侧控制面板"""
    
    # 信号定义
    color_changed = Signal(str)
    size_changed = Signal(int, int)
    download_requested = Signal()
    
    def __init__(self):
        super().__init__()
        self._setup_ui()
        self._connect_internal_signals()
        self._populate_preset_sizes()
    
    def _setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout(self)
        
        # 颜色设置组
        self._setup_color_group(layout)
        
        # 尺寸设置组
        self._setup_size_group(layout)
        
        # 格式设置组
        self._setup_format_group(layout)
        
        # 保存设置组
        self._setup_save_group(layout)
        
        # 下载按钮
        self._setup_download_button(layout)
        
        layout.addStretch()
    
    def _setup_color_group(self, parent_layout):
        """设置颜色设置组"""
        color_group = QGroupBox("颜色设置")
        color_layout = QVBoxLayout(color_group)
        
        # 颜色输入
        color_input_layout = QHBoxLayout()
        color_input_layout.addWidget(QLabel("16进制颜色:"))
        self.color_input = QLineEdit(AppConfig.DEFAULT_COLOR)
        self.color_input.setPlaceholderText("#FF0000")
        color_input_layout.addWidget(self.color_input)
        
        color_layout.addLayout(color_input_layout)
        
        # 颜色选择器按钮
        self.color_picker_btn = QPushButton("选择颜色...")
        color_layout.addWidget(self.color_picker_btn)
        
        parent_layout.addWidget(color_group)
    
    def _setup_size_group(self, parent_layout):
        """设置尺寸设置组"""
        size_group = QGroupBox("尺寸设置")
        size_layout = QVBoxLayout(size_group)
        
        # 常用尺寸选择
        preset_layout = QVBoxLayout()
        preset_layout.addWidget(QLabel("常用尺寸:"))
        
        self.preset_combo = QComboBox()
        preset_layout.addWidget(self.preset_combo)
        
        size_layout.addLayout(preset_layout)
        
        # 自定义尺寸
        custom_layout = QVBoxLayout()
        custom_layout.addWidget(QLabel("自定义尺寸:"))
        
        # 宽度设置
        width_layout = QHBoxLayout()
        width_layout.addWidget(QLabel("宽度:"))
        self.width_spin = QSpinBox()
        self.width_spin.setRange(AppConfig.MIN_WIDTH, AppConfig.MAX_WIDTH)
        self.width_spin.setValue(1920)
        width_layout.addWidget(self.width_spin)
        width_layout.addWidget(QLabel("px"))
        
        # 高度设置
        height_layout = QHBoxLayout()
        height_layout.addWidget(QLabel("高度:"))
        self.height_spin = QSpinBox()
        self.height_spin.setRange(AppConfig.MIN_HEIGHT, AppConfig.MAX_HEIGHT)
        self.height_spin.setValue(1080)
        height_layout.addWidget(self.height_spin)
        height_layout.addWidget(QLabel("px"))
        
        custom_layout.addLayout(width_layout)
        custom_layout.addLayout(height_layout)
        
        size_layout.addLayout(custom_layout)
        
        parent_layout.addWidget(size_group)
    
    def _setup_format_group(self, parent_layout):
        """设置格式设置组"""
        format_group = QGroupBox("格式设置")
        format_layout = QVBoxLayout(format_group)
        
        format_layout.addWidget(QLabel("图片格式:"))
        self.format_combo = QComboBox()
        self.format_combo.addItems(AppConfig.SUPPORTED_FORMATS)
        self.format_combo.setCurrentText(AppConfig.DEFAULT_FORMAT)
        format_layout.addWidget(self.format_combo)
        
        parent_layout.addWidget(format_group)
    
    def _setup_save_group(self, parent_layout):
        """设置保存设置组"""
        save_group = QGroupBox("保存设置")
        save_layout = QVBoxLayout(save_group)
        
        # 文件名设置
        filename_layout = QVBoxLayout()
        filename_layout.addWidget(QLabel("文件名:"))
        self.filename_input = QLineEdit()
        self.filename_input.setPlaceholderText("留空使用默认命名")
        filename_layout.addWidget(self.filename_input)
        save_layout.addLayout(filename_layout)
        
        # 保存路径
        path_layout = QVBoxLayout()
        path_layout.addWidget(QLabel("保存路径:"))
        
        self.path_input = QLineEdit(FileUtils.get_default_save_path())
        self.path_input.setReadOnly(True)
        path_layout.addWidget(self.path_input)
        
        path_btn_layout = QHBoxLayout()
        self.browse_btn = QPushButton("浏览...")
        self.open_dir_btn = QPushButton("打开目录")
        path_btn_layout.addWidget(self.browse_btn)
        path_btn_layout.addWidget(self.open_dir_btn)
        path_layout.addLayout(path_btn_layout)
        
        save_layout.addLayout(path_layout)
        
        parent_layout.addWidget(save_group)
    
    def _setup_download_button(self, parent_layout):
        """设置下载按钮"""
        self.download_btn = QPushButton("下载色块")
        self.download_btn.setStyleSheet("""
            QPushButton {
                background-color: #0078D4;
                color: white;
                font-size: 14px;
                font-weight: bold;
                padding: 10px;
                border: none;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #106EBE;
            }
            QPushButton:pressed {
                background-color: #005A9E;
            }
        """)
        parent_layout.addWidget(self.download_btn)
    
    def _connect_internal_signals(self):
        """连接内部信号"""
        self.color_input.textChanged.connect(self._on_color_changed)
        self.preset_combo.currentIndexChanged.connect(self._on_preset_changed)
        self.width_spin.valueChanged.connect(self._on_custom_size_changed)
        self.height_spin.valueChanged.connect(self._on_custom_size_changed)
        self.browse_btn.clicked.connect(self._browse_directory)
        self.download_btn.clicked.connect(self.download_requested.emit)
    
    def _populate_preset_sizes(self):
        """填充常用尺寸下拉框"""
        self.preset_combo.clear()
        self.preset_combo.addItem("自定义", None)
        
        sizes = AppConfig.get_all_common_sizes()
        for ratio, width, height in sizes:
            text = f"{width}×{height} ({ratio})"
            self.preset_combo.addItem(text, (width, height))
    
    def _on_color_changed(self, color_text: str):
        """颜色输入改变"""
        self.color_changed.emit(color_text)
    
    def _on_preset_changed(self, index: int):
        """预设尺寸改变"""
        data = self.preset_combo.currentData()
        if data:
            width, height = data
            self.width_spin.setValue(width)
            self.height_spin.setValue(height)
    
    def _on_custom_size_changed(self):
        """自定义尺寸改变"""
        current_width = self.width_spin.value()
        current_height = self.height_spin.value()
        
        match_found = False
        for i in range(1, self.preset_combo.count()):
            data = self.preset_combo.itemData(i)
            if data and data[0] == current_width and data[1] == current_height:
                self.preset_combo.setCurrentIndex(i)
                match_found = True
                break
        
        if not match_found:
            self.preset_combo.setCurrentIndex(0)
        
        self.size_changed.emit(current_width, current_height)
    
    def _browse_directory(self):
        """浏览目录"""
        directory = QFileDialog.getExistingDirectory(
            self, 
            "选择保存目录",
            self.path_input.text()
        )
        if directory:
            self.path_input.setText(directory)
    
    # 公共方法
    def get_save_directory(self) -> str:
        """获取保存目录"""
        return self.path_input.text()
    
    def get_custom_filename(self) -> str:
        """获取自定义文件名（可能为空）"""
        return self.filename_input.text().strip()
    
    def get_format_name(self) -> str:
        """获取格式名称"""
        return self.format_combo.currentText()
    
    def get_color(self) -> str:
        """获取颜色值"""
        return self.color_input.text()
    
    def get_size(self) -> tuple:
        """获取尺寸"""
        return (self.width_spin.value(), self.height_spin.value())
    
    def set_color(self, hex_color: str):
        """设置颜色值"""
        if len(hex_color) == 7 and hex_color.startswith('#'):
            self.color_input.setText(hex_color.upper())